﻿using yao.Common;
using yao.Entity;
using yao.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Titan;

namespace yao.website.Controllers
{
    /// <summary>
    /// 商品管理
    /// </summary>
    public class ProductController:BaseController
    {
        public ActionResult Index(int? p)
        {
            int pageIndex = p == null ? 1 : (int)p;
            ViewBag.PageIndex = pageIndex;

            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(Product);
                q.Selects.Add(Product_.ProductId);
                q.Selects.Add(Product_.Image60);
                q.Selects.Add(Product_.ProductName);//商品名称
                q.Selects.Add(Product_.ProductNo);//商品编号
                q.Selects.Add(Product_.BrandId);//商品品牌Id
                q.Selects.Add(Product_.CategoryId);//商品类别
                q.Selects.Add(Product_.Unit);//单位
                q.Selects.Add(Product_.Barcode);//条形码
                q.Selects.Add(Product_.Price);//标准售价
                q.Selects.Add(Product_.StoreCount);//库存数量
                q.Selects.Add(Product_.LockCount);//锁定数量
                q.Selects.Add(Product_.UseableCount);//可用数量
                q.Wheres.Add(Product_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                q.OrderBy(Product_.ProductId.Desc);
                q.PageSize = 20;
                q.PageIndex = pageIndex;
                q.ReturnMatchedCount = true;
                Products products = new Products();
                products.TotalCount = cn.SelectCollection(products.Items, q);
                return View(products);
            }
        }
        [HttpPost]
        public ActionResult GetProductBySearchKey(string key) {
            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(Product);
                q.Selects.Add(Product_.ProductId);
                q.Selects.Add(Product_.ProductName);//商品名称
                q.Selects.Add(Product_.ProductNo);//商品编号
                q.Selects.Add(Product_.Unit);//单位
                q.Selects.Add(Product_.Barcode);//条形码
                q.Selects.Add(Product_.Price);//标准售价
                q.Selects.Add(Product_.MinQuantity);//起订量
                q.Selects.Add(Product_.StoreCount);//库存数量
                q.Selects.Add(Product_.LockCount);//锁定数量
                q.Selects.Add(Product_.UseableCount);//可用数量
                q.Wheres.Add(Product_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                q.Wheres.Add(Product_.SearchKey.TLike(key));
                q.OrderBy(Product_.ProductId.Desc);
                q.PageSize = 20;
                q.PageIndex = 1;
                Products products = new Products();
                products.TotalCount = cn.SelectCollection(products.Items, q);
                return Json(products.Items);
            }
        }

        public ActionResult Edit(long? id)
        {
            Product product = new Product();
            if (id != null)
            {
                ViewBag.Title = "修改商品-" + id;
                product.ProductId = (long)id;
                using (IDbSession cn = OpenSession())
                {
                    cn.Select(product,Product_.ALL,Product_.Category.CategoryName);
                }
            }
            return View(product);
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Product product)
        {
            #region 验证
            Validate(product, Product_.ProductNo);
            Validate(product, Product_.ProductName);
            Validate(product, Product_.CategoryId);
            Validate(product, Product_.BrandName);
            Validate(product, Product_.Price);
            Validate(product, Product_.MinQuantity);
            Validate(product, Product_.StoreCount);
            Validate(product, Product_.Unit);
            Validate(product, Product_.PackageCount);
            Validate(product, Product_.ShelfLife);
            Validate(product, Product_.ShelfLifeUnitId);
            Validate(product, Product_.IsActive);
            Validate(product, Product_.IsImported);
            Validate(product, Product_.IsPromotion);
            #endregion
            if (!IsValid)
            {
                return View(product);
            }

            #region 商品图片
            string images = Request.Form["Images"];
            if (!string.IsNullOrEmpty(images)) {
                string[] imgs = images.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                product.Image60 = imgs[0];
                product.Image200 = imgs[1];
                product.Image400 = imgs[2];
            }
            #endregion

            using (IDbSession cn = OpenSession())
            {
                try
                {
                    cn.BeginTransaction();

                    product.CompanyId = CurrentEmployee.CompanyId;
                    product.SearchKey = CommonFun.GetHeadOfSingleChs(product.ProductName[0].ToString());//商品名称首字母
                    
                    #region 品牌（如果在品牌表不存在，就添加到品牌表）
                    QueryExpression query = new QueryExpression();
                    query.EntityType = typeof(Brand);
                    query.Selects.Add(Brand_.BrandId);
                    query.Wheres.Add(Brand_.BrandName.TEqual(product.BrandName));
                    Brands brands = new Brands();
                    cn.SelectCollection(brands.Items, query);
                    if (brands.Items.Count <= 0)
                    {
                        Brand brand = new Brand
                        {
                            BrandName = product.BrandName
                        };
                        cn.Insert(brand);
                        product.BrandId = brand.BrandId;
                    }
                    else
                    {
                        product.BrandId = brands.Items[0].BrandId;
                    }
                    #endregion

                    //添加
                    if (product.ProductId == 0)
                    {
                        #region validate
                        ConditionExpressionCollection cs = new ConditionExpressionCollection();
                        cs.Add(Product_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                        cs.Add(Product_.ProductNo.TEqual(product.ProductNo));
                        if (cn.Exists<Product>(cs))
                        {
                            AddFormError(Product_.ProductNo, "商品编号不允许重复");
                        }
                        if (!IsValid) return View(product);
                        #endregion

                        cn.Insert(product);
                    }
                    else
                    {
                        #region validate
                        ConditionExpressionCollection cs = new ConditionExpressionCollection();
                        cs.Add(Product_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                        cs.Add(Product_.ProductNo.TEqual(product.ProductNo));
                        cs.Add(Product_.ProductId.TNotEqual(product.ProductId));
                        if (cn.Exists<Product>(cs))
                        {
                            AddFormError(Product_.ProductNo, "商品编号不允许重复");
                        }
                        if (!IsValid) return View(product);
                        #endregion

                        product.UpdateTime = DateTime.Now;
                        cn.Update(product, Product_.ProductNo, Product_.ProductName, Product_.CategoryId, Product_.BrandId, Product_.Image200, Product_.Image400, Product_.Image60, Product_.Barcode, Product_.ShelfLife, Product_.ShelfLifeUnitId, Product_.Price, Product_.MinQuantity,  Product_.Unit, Product_.PackageCount, Product_.IsActive, Product_.IsPromotion, Product_.UpdateTime, Product_.Description, Product_.Remark);
                    }
                    cn.Commit();
                }
                catch (Exception ex)
                {
                    cn.Rollback();
                    throw new BusinessException(ex.Message);
                }
            }
            return new IframeResult(Url.Action("Edit"), Url.Action("Index"));
        }
        

        #region 详情
        public ActionResult Detail(long id)
        {
            Product product = new Product();
            if (id>0)
            {
                ViewBag.Title = "商品详情-" + id;
                product.ProductId = (long)id;
                using (IDbSession cn = OpenSession())
                {
                    cn.Select(product);
                }
            }
            return View(product);
        }
        #endregion

        #region 删除
        [HttpPost]
        public ActionResult Delete(long id)
        {
            Product product = new Product { ProductId = id };
            bool ret = false;

            using (IDbSession cn = OpenSession())
            {
                ret = cn.Delete(product) > 0;
            }
            return Json(new { ret = ret });
        }
        #endregion

        #region 线下启用
        [HttpPost]
        public ActionResult Active(long id, bool isActive)
        {
            Product product = new Product {
                ProductId = id,
                IsActive=isActive
            };
            bool ret = false;

            using (IDbSession cn = OpenSession())
            {
                ret = cn.Update(product, Product_.IsActive) > 0;
            }
            return Json(new { ret = ret });
        }
        #endregion

    }
}                                                                               
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                
                                                                                